package com.lc.projects.sample.plan.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.dom.DOMText;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class TestXml {
	@Test
	public void createXml(){
		File file = new File("d:\\test.xml");
		if(file.exists()){
			file.delete();
		}
		
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("Root");
		root.addAttribute("root", "true");
		
		Element element1 = root.addElement("student");
		element1.addText("name");
		element1.addAttribute("attr1", "test");
		
		
		Element element2 = root.addElement("student2");
		DOMText text = new DOMText("lc");
		element2.add(text);
		
		Element ele21 = element2.addElement("son");
		ele21.addText("test");
		ele21.addCDATA("This is a CDATA.");
		
		
		OutputFormat format = new OutputFormat("    ", true);
		format.setEncoding("UTF-8");
		XMLWriter xmlWriter;
		try {
			xmlWriter = new XMLWriter(new FileOutputStream(file),format);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void readXml(){
		File file = new File("d:\\test.xml");
		if(!file.exists()){
			System.out.println("文件不存在...");
			return ;
		}
		
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();
		System.out.println("root:"+root.getName());
		
		parseElement(root);
	}
	
	
	@SuppressWarnings("unchecked")
	public void parseElement(Element element){
		if(element != null){
			Iterator<Element> it = element.elementIterator();
			while(it.hasNext()){
				Element e = it.next();
				parseElement(e);
			}
			System.out.println(element.getName() + " "+element.getText());
		}
		
	}
}
